package cn.easyplatform.studio.cmd.importAll;

import cn.easyplatform.studio.StudioException;
import cn.easyplatform.studio.dao.DaoException;
import cn.easyplatform.studio.interceptor.Command;
import cn.easyplatform.studio.interceptor.CommandContext;
import cn.easyplatform.studio.vos.MessageVo;

import java.util.ArrayList;
import java.util.List;

public class SaveMessageInfoCmd implements Command<Boolean> {
    private List<MessageVo> voList;
    private List<MessageVo> updateDicVos = new ArrayList<>();
    private List<MessageVo> addDicVos = new ArrayList<>();
    public SaveMessageInfoCmd(List<MessageVo> voList) {
        this.voList = voList;
    }

    @Override
    public Boolean execute(CommandContext cc) {
        List<MessageVo> list = cc.getMessageInfoDao(null).selectList( "select * from sys_message_info where 1=1",null);

        List<String> dicKeyList = new ArrayList<>();
        for (MessageVo vo: list) {
            dicKeyList.add(vo.getCode());
        }
        parseData(voList, dicKeyList);

        try {
            cc.beginTx();
            cc.getMessageInfoDao(null).setMessageInfoList(addDicVos);
            cc.getMessageInfoDao(null).updateMessageInfoList(updateDicVos);
            cc.commitTx();
        } catch (Exception ex) {
            cc.rollbackTx();
            if (ex instanceof DaoException)
                throw (DaoException) ex;
            throw new StudioException("ExportCmd:" + ex.getMessage());
        } finally {
            cc.closeTx();
        }
        return Boolean.TRUE;
    }

    private void parseData(List<MessageVo> vos, List<String> allDicVoList) {
        for (MessageVo vo: vos) {
            if (allDicVoList.contains(vo.getCode()))
                updateDicVos.add(vo);
            else
                addDicVos.add(vo);
        }
    }
}
